import React,{ useEffect } from 'react';
import { View } from 'react-native';
import { AllForOne,GQL,useMutation,useLazyQuery } from '../../network';
import { observer } from 'mobx-react';
import {when } from 'mobx';

import useAutoSignIn from '../useAutoSignIn';

// store
import OneForAllStore from './OneForAllStore';
import RunExecutor,{executorKeys} from './RunExecutor';
import DataCenter from './DataCenter';


interface Props {
    client: any
}

const OneForAllMountPoint = observer((props:Props) => {
    /**
     *  Data Control Center
     */
    const [queryAssets,{
            data:Data_queryAssets,
            loading:Loading_queryAssets,
            error:Error_queryAssets,
            refetch: AssetsRefetch,
        }] = useLazyQuery(AllForOne.userAssets);
    
    const [mutateGolds] = useMutation(AllForOne.GoldReward);

    /**
     *  Data Dealing Center
     */
    function QAssetsExecutor(userId: number){
        if(!OneForAllStore.QAssetsExecuted){
            //Execute the query action for the first time
            queryAssets({
                variables:{id: userId}
            })
        }else{
            AssetsRefetch({variables:{id: userId}})
                .then(rs => {
                    let assets:DCAssets = rs?.data?.user ?? {}
                    DataCenter.setAssets(assets);
                })
        }
    }

    function MGoldsExecutor(videoIds: number[]){
        mutateGolds({
            variables:{
                input: {video_ids: [videoIds]}
            }
        })
    }

    /**
     *  Data Execute Monitor
     */
    useEffect(() => {
        QAssetsExecutor(1)
        if(!Loading_queryAssets){
            if(Data_queryAssets){
                //TODO: 更新datacenter的值
            }
        }
    },[Data_queryAssets,Loading_queryAssets,Error_queryAssets])

    when(
        () => !OneForAllStore.AssetsStandBy,
        () => {
            AssetsRefetch({variables: {id: 1}})
                .then(rs => {
                    //TODO: 更新 dataCenter的值
                });
            //每个监视者执行到这都要将 OneForAllStore 里的standby重置
            RunExecutor(executorKeys.standbyAssets);
        }
    )

    async function _init(){

    }

    /**
     *  初始化 effect , 静默登录处理
     */
    useAutoSignIn({client: props.client});

    return (
        <View />
    )
});

export default OneForAllMountPoint;